#!/usr/bin/env python3
"""
admin密码重置工具 - 使用指定密码 A1##B2
这个脚本会临时降低密码强度要求来重置admin密码
"""
import sys
import os
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from sqlalchemy.orm import Session
from core.database import engine, SessionLocal
from models.database import User
from core.auth import get_password_hash
from datetime import datetime
from core.config import get_settings
settings = get_settings()
default_admin_password = settings.default_admin_password

def reset_admin_with_specific_password(default_admin_password):
    """重置admin密码为A1##B2##"""
    target_password = default_admin_password
    
    try:
        # 创建数据库会话
        db = SessionLocal()
        
        # 查找admin用户
        admin_user = db.query(User).filter(User.username == "admin").first()
        
        if not admin_user:
            print("❌ 未找到admin用户，正在创建...")
            
            # 创建admin用户
            admin_user = User(
                username="admin",
                password_hash=get_password_hash(target_password),
                email="admin@example.com",
                role="admin",
                is_active=True
            )
            db.add(admin_user)
            db.commit()
            db.refresh(admin_user)
            
            print(f"✅ Admin用户创建成功！")
            
        else:
            # 重置密码
            admin_user.password_hash = get_password_hash(target_password)
            admin_user.updated_at = datetime.now()
            db.commit()
            
            print(f"✅ Admin密码重置成功！")
            
        print(f"   用户名: admin")
        print(f"   新密码: {target_password}")
        print(f"   密码哈希: {admin_user.password_hash[:20]}...")
        print("")
        print("🎯 现在可以使用以下信息登录系统:")
        print("   用户名: admin")
        print(f"   密码: {target_password}")
        print("")
        print("⚠️  注意: 此密码不符合新的密码强度要求，")
        print("   建议登录后立即修改为更强的密码！")
        
        return True
        
    except Exception as e:
        print(f"❌ 重置密码时发生错误: {e}")
        return False
    finally:
        db.close()

def verify_password_reset(password):
    """验证密码重置是否成功"""
    try:
        db = SessionLocal()
        admin_user = db.query(User).filter(User.username == "admin").first()
        
        if admin_user:
            from core.auth import verify_password
            is_valid = verify_password(password, admin_user.password_hash, client_hashed=False)
            print(f"🔍 密码验证结果: {'✅ 成功' if is_valid else '❌ 失败'}")
            return is_valid
        else:
            print("❌ 未找到admin用户")
            return False
            
    except Exception as e:
        print(f"❌ 验证密码时发生错误: {e}")
        return False
    finally:
        db.close()

def main():
    """主函数"""
    print("🔐 Admin密码重置工具")
    print("=" * 50)
    print(f"⚠️  警告: 此工具将admin密码重置为 {default_admin_password}")
    print("   此密码不符合新的密码强度要求！")
    print("")
    
    print("正在重置admin密码...")
    
    # 重置密码
    if reset_admin_with_specific_password(default_admin_password):
        print("\n" + "=" * 50)
        print("🔍 验证密码重置...")
        
        # 验证密码
        if verify_password_reset(default_admin_password):
            print("\n🎉 密码重置并验证成功！")
            print(f"现在可以使用 admin/{default_admin_password} 登录系统了")
        else:
            print("\n❌ 密码验证失败，请检查系统配置")
    else:
        print("\n❌ 密码重置失败！")

if __name__ == "__main__":
    main()